import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { GetListDto } from 'src/interface';
import { Resource, ResourceDocument } from 'src/models/resource';

@Injectable()
export class ResourceService {
  constructor(
    @InjectModel('Resource') private resourceModel: Model<ResourceDocument>,
  ) {}

  async getCount(): Promise<number> {
    return this.resourceModel.find().estimatedDocumentCount();
  }

  /* 查询所有数据 */
  async findAll(): Promise<Resource[] | null> {
    return await this.resourceModel
      .find()
      .populate('parentId')
      .sort({ sort: 1 });
  }

  /* 分页查询数据 */
  async findList(getListDto: GetListDto): Promise<Resource[] | null> {
    return await this.resourceModel
      .find()
      .populate('parentId')
      .skip((getListDto.pageIndex - 1) * getListDto.pageSize)
      .limit(getListDto.pageSize)
      .sort({ sort: 1 });
  }

  /* 添加数据 */
  async createData(createDto: Resource): Promise<Resource> {
    const createdUser = new this.resourceModel(createDto);
    return await createdUser.save();
  }

  /* 查询单条数据 */
  async findOne(id: string): Promise<any> {
    return await this.resourceModel.findById(id);
  }

  /* 更新数据 */
  async updateData(id: string, upDataUserDto: Resource): Promise<any> {
    return await this.resourceModel.findByIdAndUpdate(id, upDataUserDto);
  }

  /* 删除数据 */
  async removeData(id: string): Promise<any> {
    return await this.resourceModel.findByIdAndDelete(id);
  }

  /* 批量删除数据 */
  async deleteData(deleteMenusDto: string[]): Promise<any> {
    return await this.resourceModel.deleteMany({
      _id: { $in: deleteMenusDto },
    });
  }
}
